const fs = require('fs');
const qiniu = require("qiniu");
const intformat = require('biguint-format');
const FlakeId = require('flake-idgen');
const flakeIdGen = new FlakeId();
const Busboy = require('busboy');
const Promise = require('bluebird');
const request = require('request');

module.exports = function (config) {
    let {fetch, upload} = config.paths;

    let uploadParams = function (settings, type) {
        let bucket, domain;
        let access_key = settings.access_key;
        let secret_key = settings.secret_key;

        if (type == 'file') {
            bucket = settings.file_bucket;
            domain = settings.file_domain;
        } else if (type == 'ue') {
            bucket = settings.ue_bucket;
            domain = settings.ue_domain;
        } else if (type == 'user') {
            bucket = settings.user_bucket;
            domain = settings.user_domain;
        } else {
            bucket = settings.image_bucket;
            domain = settings.image_domain;
        }

        let mac = new qiniu.auth.digest.Mac(access_key, secret_key);
        let uptoken = new qiniu.rs.PutPolicy({scope: bucket}).uploadToken(mac);
        return Promise.resolve({
            uptoken: uptoken,
            bucket: bucket,
            domain: domain
        });
    }

    let apis = {
        /**
         * 获取上传参数
         */
        uploadParams: uploadParams,

        /**
         * 表单上传
         */
        formUpload: function (req, settings, type) {
            return new Promise(function (resolve) {
                let body = {}, busboy = new Busboy({headers: req.headers});
                busboy.on('field', function (fieldname, val) {
                    body[fieldname] = val;
                });
                busboy.on('file', function (fieldname, file, filename) {
                    let lastIndex = filename.lastIndexOf('.');
                    let suffix = lastIndex == -1 ? '' : filename.substr(lastIndex);
                    let name = intformat(flakeIdGen.next(), 'dec') + suffix;
                    let saveTo = upload + name;

                    file.pipe(fs.createWriteStream(saveTo));
                    file.on('end', function () {
                        //七牛上传
                        return uploadParams(settings, type).then(function (params) {

                            let config = new qiniu.conf.Config();
                            let formUploader = new qiniu.form_up.FormUploader(config);
                            let putExtra = new qiniu.form_up.PutExtra();

                            formUploader.putFile(params.uptoken, name, saveTo, putExtra, function (err, ret) {
                                if (!err) {
                                    let file = {
                                        filename: filename,
                                        name: name,
                                        domain: params.domain,
                                        bucket: params.bucket,
                                        key: ret.key,
                                        url: params.domain + name
                                    }
                                    resolve({success: true, data: body, file: file});
                                } else {
                                    console.error(err);
                                    resolve({success: false});
                                }
                            });
                        });
                    });
                });
                req.pipe(busboy);
            });
        },

        /**
         * 图片地址数组上传
         */
        imagesUpload: function (settings, images, image_type, type) {
            if (!images || !images.length) {
                return Promise.resolve([]);
            }
            //七牛上传
            return uploadParams(settings, type).then(function (params) {
                let all = [];
                let handle = function (image, order_by) {
                    all.push(new Promise(function (resolve, reject) {
                        if (image.indexOf('//') == 0) {
                            image = 'http:' + image;
                        }
                        let lastIndex = image.lastIndexOf('.');
                        let suffix = image.lastIndexOf('.') == -1 ? '' : image.substr(lastIndex).toLocaleLowerCase();
                        if (suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png') {
                            suffix = '';
                        }
                        let name = intformat(flakeIdGen.next(), 'dec') + suffix;
                        let saveTo = fetch + name;

                        request.get(image).on('end', function () {

                            let config = new qiniu.conf.Config();
                            let formUploader = new qiniu.form_up.FormUploader(config);
                            let putExtra = new qiniu.form_up.PutExtra();

                            formUploader.putFile(params.uptoken, name, saveTo, putExtra, function (err, ret) {
                                if (err) {
                                    return reject(err);
                                }

                                return resolve({
                                    type: image_type,
                                    bucket: params.bucket,
                                    key: ret.key,
                                    image: params.domain + name,
                                    order_by: order_by
                                });
                            });
                        }).pipe(fs.createWriteStream(saveTo));
                    }));
                }
                for (let i in images) {
                    handle(images[i], i);
                }
                return Promise.all(all);
            });
        },

        /**
         * 上传头像
         */
        portraitUpload: function (qiniuConfig, headimgurl) {
            if (!headimgurl) {
                return Promise.resolve({success: false});
            }
            let {user_mirror, user_domain} = qiniuConfig;
            if (user_mirror && headimgurl.indexOf(user_mirror) != -1) {
                return Promise.resolve({success: true, image: headimgurl.replace(user_mirror, user_domain)});
            }
            return apis.imagesUpload(qiniuConfig, [headimgurl], 'UserImage', 'user').then(function (images) {
                if (!images || !images.length) {
                    return Promise.resolve({success: false});
                }
                return {success: true, image: images[0].image};
            });
        }
    }


    return apis;
};